package org.shj.thread.book1.filesize;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * Java 7 版本开始
 * @author Administrator
 *
 */
public class ForkJoinFileSize {

	private final static ForkJoinPool forkJoinPool = new ForkJoinPool();
	
	private static class FileSizeFinder extends RecursiveTask<Long>{
		private static final long serialVersionUID = -7613134403984328732L;
		final File file;
		
		public FileSizeFinder(final File file){
			this.file = file;
		}
		
		public Long compute(){
			long size = 0;
			if(file.isFile())
				size = file.length();
			else{
				File[] children = file.listFiles();
				if(children  != null){
					List<ForkJoinTask<Long>> tasks = new ArrayList<>();
					for(final File child : children){
						if(child.isFile())
							size += child.length();
						else{
							tasks.add(new FileSizeFinder(child));
						}
					}
					
					for(ForkJoinTask<Long> task : invokeAll(tasks)){
						size += task.join();
					}
				}
			}
			
			return size;
		}
	}
	
	public static void main(String[] args)throws Exception{
		long start = System.nanoTime();
		String fileName = "D:\\mavenrepos\\repository\\org";
		long total = forkJoinPool.invoke(new FileSizeFinder(new File(fileName)));
		long end = System.nanoTime();
		
		System.out.println("Total size: " + total);
		System.out.println("Time taken: " + (end - start)/1.0e9);
	}
}

